<?php

namespace App\Imports;

use App\Models\Client;
use App\Models\ClientCar;
use App\Models\CarBrand;
use App\Models\CarSerie;
use App\Models\CarModel;
use Illuminate\Support\Collection;
use Maatwebsite\Excel\Concerns\ToCollection;
use Maatwebsite\Excel\Concerns\WithChunkReading;
use Illuminate\Contracts\Queue\ShouldQueue;

class ClientImport implements ToCollection,WithChunkReading,ShouldQueue
{
    public function collection(Collection $rows)
    {

        $rows->shift();
        $rows->shift();
        $car_type_id['小型车']     = 1;
        $car_type_id['大中型客车'] = 2;
        $car_type_id['轻型货车']   = 3;
        $car_type_id['大型货车']   = 4;
        $car_type_id['挂车']       = 5;
        $car_type_id['其他'] = 6;

        //dd($rows);
        foreach ($rows as $row) 
        {
            if(empty($row[0])) continue;
           
            $clientData['name']  = trim($row[0]);
            $clientData['phone'] = trim($row[1]);
           
            $client = Client::where($clientData)->first();
            
            if(empty($client)) {
                $clientData['code']  = date('YmdHis').str_random(4);
                $client = Client::create($clientData);    
            }
            

            if(empty($row[3])) continue;
            $carData = [
                'client_id' => $client->id,
                'car_num'   => $row[3],
            ];

            $had = ClientCar::where($carData)->first();
            if($had) continue;
            
            if($row[4]) {
                $brand_id = CarBrand::where('name',trim($row[4]))
                                    ->value('id');
                if($brand_id) $carData['car_brand_id'] = $brand_id;
            }

            if($row[5]) {
                $serie_id = CarSerie::where('name',trim($row[5]))
                                    ->value('id');
                if($serie_id) $carData['car_serie_id'] = $serie_id;
            }

            if($row[6]) {
                $model_id = CarModel::where('name',trim($row[6]))
                                    ->value('id');
                if($model_id) $carData['car_model_id'] = $model_id;
            }

            $carData['vin']         = $row[7];
            $carData['engine_num']  = $row[8];
            if($row[9]) {
                $carData['car_type_id'] = array_get($car_type_id,$row[9]);    
            }
            
            //dd($carData,$car_type_id,$row[9]);
            ClientCar::create($carData);


        }


    }

    public function chunkSize(): int
    {
        return 30;
    }
}
